package com.xy.netutils.net;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by 向阳 on 2016/11/23.
 * email：yang.xiang@cienet.com.cn
 */

public class NetUtils {

    private static final long DEFAULT_TIMEOUT = 8;
    private final String BASE_URL = "http://op.juhe.cn/onebox/";
    private static NetUtils INSTANCE;
    private final Retrofit retrofit;
    public static NetService netService = null;

    private NetUtils() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();
        netService = retrofit.create(NetService.class);
    }


    //获取单例
    public static NetService getInstance() {
        if (null == INSTANCE) {
            INSTANCE = new NetUtils();
        }
        return netService;
    }

    public static   void  toSubscribe(Observable o, Subscriber s) {
                 o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);

    }
}
